package com.zelin.dao.dyna;

import com.zelin.dao.UserDao;
import com.zelin.dao.impl.UserDaoImpl;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;
import java.util.zip.CheckedInputStream;

public class UserDaoCGLIBDynaProxyImpl implements MethodInterceptor {
    //生成代理对象
    public UserDao createUserDao(){
        //1. 构造 一个Enhancer对象
        Enhancer enhancer = new Enhancer();
        //2. 设置父类
        enhancer.setSuperclass(UserDaoImpl.class);
        //设置回调
        enhancer.setCallback(this);
        //创建目标对象
        Object o = enhancer.create();
        return (UserDao) o;
    }
    //调用目标对象的方法
    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
       //得到方法名
        String name = method.getName();
        //判断是否是query
        if (name.equalsIgnoreCase("query")){
            checkSecurity();
        }
        return methodProxy.invokeSuper(o,objects);
    }

    private void checkSecurity() {
        System.out.println("使用CGLIB进行安全性检查-----");
    }
}
